<script setup lang="ts">
import {ref, watch, computed, reactive} from 'vue'
import type {FormInst, FormItemRule, TreeSelectOption} from 'naive-ui'
import {useMessage} from "naive-ui";
import CustomModal from '@/components/CustomModal'
import {postOrputRequest} from "@/api";

const typeOptions = [
  {label: '目录', value: 1},
  {label: '菜单', value: 2},
  {label: '按钮', value: 3}
] as const

type MenuType = typeof typeOptions[number]['value']

interface MenuItem {
  id: number
  label: string | null
  name: string | null
  p_id: number | null
  types: MenuType
  code: string | null
  e_link: 0 | 1
  url: string | null
  is_hide: 0 | 1
  icon: string | null
  sort: number | null
}

const message = useMessage()
const visible = defineModel('visible', {type: Boolean, default: false})
const props = defineProps<{
  formData?: Recordable;
  parentTreeSelectOption: TreeSelectOption[];
}>();

const emits = defineEmits(["closeModal"])

const handelSubmitLoading = ref<boolean>(false)
const formRef = ref<FormInst | null>(null)

const addEditForm = reactive<MenuItem>({
  id: 0,
  label: null,
  name: null,
  p_id: null,
  types: 1,
  code: null,
  e_link: 0,
  url: null,
  is_hide: 0,
  icon: null,
  sort: 100,
})
// 默认表单值，用于重置
const defaultFormValues: MenuItem = {
  id: 0,
  label: null,
  name: null,
  p_id: null,
  types: 1,
  code: null,
  e_link: 0,
  url: null,
  is_hide: 0,
  icon: null,
  sort: 100,
}

const addEditFormRules = computed(() => {
  const rules: Record<string, FormItemRule> = {
    types: {
      type: 'number',
      required: true,
      message: '请选择类型',
      trigger: 'change'
    },
    p_id: {
      type: 'number',
      required: true,
      message: '请选择上级',
      trigger: 'change'
    },
    label: {
      required: true,
      message: addEditForm.types === 1 ? '请填写目录标题' :
          addEditForm.types === 2 ? '请填写菜单标题' : '请填写按钮标题',
      trigger: ['input', 'blur']
    },
  }

  // 根据类型动态添加规则
  if (addEditForm.types !== 3) {
    rules.name = {
      required: true,
      trigger: ['input', 'blur'],
      validator: (_rule: FormItemRule, value: string) => {
        return new Promise<void>((resolve, reject) => {
          const regex = /^[A-Za-z]+$/
          if (!value) {
            reject(Error('请填写路由名称'))
          } else if (!regex.test(value)) {
            reject(Error('请填写英文路由名称'))
          } else {
            resolve()
          }
        })
      }
    }
  }

  if (addEditForm.types === 2) {
    rules.url = {
      required: true,
      message: '请填写组件地址',
      trigger: ['input', 'blur']
    }
  }

  if (addEditForm.types=== 2 || addEditForm.types === 3) {
    rules.code = {
      required: true,
      message: '请填写权限码',
      trigger: ['input', 'blur']
    }
  }

  return rules
})

const modalTitle = computed(() => {
  const typeOption = typeOptions.find(item => item.value === addEditForm.types)
  return typeOption?.label || ''
})

const permissionPlaceholder = computed(() => {
  if (addEditForm.types === 1) {
    return '请填写权限码 如:admin:lists'
  } else if (addEditForm.types === 2) {
    return '请填写权限码 如:admin:lists'
  } else {
    return '请填写权限码 如:admin:add'
  }
})

//确认提交数据
const confirmBtn = () => {
  formRef.value?.validate((errors) => {
    if (!errors) {
      handelSubmitLoading.value = true;
      postOrputRequest('/menus/save', addEditForm).then((res: ResponseResult) => {
        if (res.code === 200) {
          message.success(res.message, {
            duration: 1500,
            onLeave() {
              visible.value = false
              emits('closeModal', addEditForm.id ? 2 : 1)
            }
          })
        } else {
          message.error(res.message);
          handelSubmitLoading.value = false;
        }
      })
    }
  })
}
// 关闭模态框
const closeModal = () => {
  // 使用Object.assign快速重置表单
  Object.assign(addEditForm, defaultFormValues)
  handelSubmitLoading.value = false
}

watch(() => props.formData, (newValue) => {
  if (newValue && Object.keys(newValue).length > 0) {
    Object.assign(addEditForm, {
      ...defaultFormValues,
      ...newValue
    })
  }
}, {immediate: true, deep: true})


</script>

<template>
  <custom-modal v-model:show="visible"
                :widths="680"
                :handel-submit-loading="handelSubmitLoading"
                @confirm="confirmBtn"
                @after-leave="closeModal"
                confirmText="确认"
                :title="`${addEditForm.id?'编辑':'新增'}${modalTitle}`">
    <template #default>
      <n-form ref="formRef"
              :model="addEditForm"
              :rules="addEditFormRules"
              label-width="65"
              require-mark-placement="left"
              label-placement="left">
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="类型" path="type">
            <n-button-group>
              <template v-for="(item,index) in typeOptions" :key="index">
                <n-button :type="item.value==addEditForm.types?'primary':'default'"
                          @click="()=>(addEditForm.types=item.value)">{{ item.label }}
                </n-button>
              </template>
            </n-button-group>
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="上&nbsp;&nbsp;&nbsp;级" path="p_id">
            <n-tree-select
                v-model:value="addEditForm.p_id"
                :options="props.parentTreeSelectOption"
                :placeholder="`请选择上级${addEditForm.types==1 || addEditForm.types==2?'目录':'菜单'}`"
            />
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="标题" path="label">
            <n-input v-model:value="addEditForm.label" :placeholder="`请填写${modalTitle}标题`" clearable/>
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="名&nbsp;&nbsp;&nbsp;称" path="name" v-if="addEditForm.types!=3">
            <n-input v-model:value="addEditForm.name" placeholder="请填写名称 只支持英文" clearable/>
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="权限码" path="code" v-if="addEditForm.types==3">
            <n-input v-model:value="addEditForm.code" :placeholder="permissionPlaceholder" clearable/>
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24" v-if="addEditForm.types==2">
          <n-form-item-gi :span="12" label="组件" path="url">
            <n-input v-model:value="addEditForm.url" placeholder="请填写组件 如:/settings/menus" clearable/>
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="权限码" path="code">
            <n-input v-model:value="addEditForm.code"
                     :placeholder="`请填写权限码 如:admin:${addEditForm.types==2?'lists':'add'}`" clearable/>
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24" v-if="addEditForm.types!=3">
          <n-form-item-gi :span="12" label="图标" path="icon">
            <n-input v-model:value="addEditForm.icon" placeholder="请填写图标" clearable/>
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="显&nbsp;&nbsp;&nbsp;示" path="is_hide">
            <n-button-group>
              <n-button :type="addEditForm.is_hide==0?'primary':'default'" @click="()=>(addEditForm.is_hide=0)">
                显示
              </n-button>
              <n-button :type="addEditForm.is_hide==1?'primary':'default'" @click="()=>(addEditForm.is_hide=1)">
                不显示
              </n-button>
            </n-button-group>
          </n-form-item-gi>
        </n-grid>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="序号" path="sort" :show-feedback="false">
            <n-input-number v-model:value="addEditForm.sort" placeholder="请填写序号" :min="0" :precision="0"
                            :show-button="false" clearable/>
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </template>
  </custom-modal>
</template>

<style scoped lang="scss">

</style>